package rest

import (
	"context"
	"fmt"

	"gitee.com/zatto/project/tree/master/vblog/api/apps/blog"
	"github.com/infraboard/mcube/client/rest"
)

func (c *Client) CreateBlog(ctx context.Context, in *blog.CreateBlogRequest) (*blog.Blog, error) {
	ins := &blog.Blog{}
	err := c.c.Post("blogs").Body(in).Do(ctx).Into(ins)
	if err != nil {
		return nil, err
	}
	return ins, nil
}

func (c *Client) QueryBlog(ctx context.Context, in *blog.QueryBlogRequest) (*blog.BlogSet, error) {
	set := &blog.BlogSet{}
	req := c.c.Get("blogs")
	if in.Status != nil {
		req = req.Param("status", in.Status.String())
	}
	err := req.
		Param("page_size", fmt.Sprintf("%d", in.PageSize)).
		Param("page_number", fmt.Sprintf("%d", in.PageNumber)).
		Param("keywords", in.Keywords).
		Param("author", in.Author).
		Do(ctx).
		Into(set)
	if err != nil {
		return nil, err
	}
	return set, nil
}

func (c *Client) DescribeBlog(ctx context.Context, in *blog.DescribeBlogRequest) (*blog.Blog, error) {
	ins := &blog.Blog{}
	err := c.c.Get(fmt.Sprintf("blogs/%d", in.Id)).Do(ctx).Into(ins)
	if err != nil {
		return nil, err
	}
	return ins, nil
}

func (c *Client) UpdateBlog(ctx context.Context, in *blog.UpdateBlogRequest) (*blog.Blog, error) {
	var req *rest.Request
	ins := &blog.Blog{}

	switch in.UpdateMode {
	case blog.PUT:
		req = c.c.Put(fmt.Sprintf("blogs/%d", in.Id))
	case blog.PATCH:
		req = c.c.Patch(fmt.Sprintf("blogs/%d", in.Id))
	default:
		return nil, fmt.Errorf("not support method")
	}

	err := req.Body(in).Do(ctx).Into(ins)
	if err != nil {
		return nil, err
	}
	return ins, err
}

func (c *Client) DeleteBlog(ctx context.Context, in *blog.DeleteBlogRequest) (*blog.Blog, error) {
	ins := &blog.Blog{}
	err := c.c.Delete(fmt.Sprintf("blogs/%d", in.Id)).Do(ctx).Into(ins)
	if err != nil {
		return nil, err
	}
	return ins, nil
}
